#include "socket_tcpserver.h"
#include "hilog.h"

VOID* CTcpSvrReq::clone()
{
	CTcpSvrReq* req = new CTcpSvrReq();
	*req = *this;
	return req;
}

BOOL CTcpSvrReq::initialize(STRCPP svrip, WORD16 svrport, BOOL block) 
{
	WORD32      opt  = 1;
	SOCKADDRIN  addr = {0};
	SOCKFD      fd   = INVALIDFD;
	//创建socket
	fd = socket(AF_INET, SOCK_STREAM, 0);
	if(-1 == fd)
	{
		perror("socket failed");
		return FALSE;
	}
	//设置地址重用
	setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (CHAR*)&opt, sizeof(opt));
	addr.sin_family      = AF_INET;
	addr.sin_port        = htons(svrport);
	addr.sin_addr.s_addr = ("" == svrip ? htonl(INADDR_ANY) : inet_addr(svrip.c_str()));
	//绑定ip地址和端口
	if(-1 == bind(fd, (SOCKADDR*)&addr, sizeof(addr)))
	{
		perror("bind failed");
		close(fd);
		return FALSE;
	}
	//开始监听
    if(-1 == listen(fd, 64))
	{
		perror("listen failed");
		close(fd);
		return FALSE;
	}
    local_addr_.setaddr(fd, svrip, svrport);
	if(!block)
	{
        local_addr_.set_noblock();
	}

    hi_trace("start http server at port %d success", svrport);
	return TRUE;
}

BOOL CTcpSvrReq::activate(BOOL block)
{
	SOCKFD     sockfd = -1;
	SOCKADDRIN addrin = {0};
	WORD32     addlen = sizeof(addrin);

    if(INVALIDFD == local_addr_.fd)
	{
		cout << "activate failed, fd invalid" << endl;
		return FALSE;
	}
    sockfd = accept(local_addr_.fd, (SOCKADDR*)&addrin, &addlen);
	if(-1 == sockfd)
	{
		perror("accept failed");
		return FALSE;
	}
	else
	{
        set_peer_addr(sockfd);
		if(!block)
		{
            peer_addr_.set_noblock();
		}
        //cout << "connect accept: " << peer_addr_.addr() << endl;
		return TRUE;
	}
}

BOOL CTcpSvrReq::receive()
{
    if(readinfo(recv_buff_))
	{
		return TRUE;
	}
	return FALSE;
}

BOOL CTcpSvrReq::process()
{
	STRCPP line;
    if(getline(recv_buff_, line))
	{
		cout << get_current_time() << " ";
        cout << peer_addr_.addr() << " ";
		cout << line << endl;  // getline去掉了\n 所以这里需要endl才能输出到屏幕
	}
	return TRUE;
}






